import 'package:flustars/flustars.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_nb_net/flutter_net.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:tracker/common/enums/LoginTypeEnum.dart';
import 'package:tracker/common/enums/user_type_enum.dart';
import 'package:tracker/common/extension/global_key_extension.dart';
import 'package:tracker/common/log/x_logger.dart';
import 'package:tracker/pages/login/mixin/login_page_mixin.dart';
import 'package:tracker/pages/login/model/login_resp.dart';
import 'package:tracker/pages/login/widget/login_form.dart';
import 'package:tracker/provider/global_provider.dart';
import 'package:tracker/provider/global_state_provider.dart';
import 'package:tracker/router/router_manager.dart';
import 'package:tracker/theme/app_theme.dart';
import 'package:tracker/utils/toast_utils.dart';
import 'package:tracker/utils/upgrade_utils.dart';

class LoginPage extends ConsumerStatefulWidget {
  const LoginPage({super.key});

  @override
  ConsumerState<LoginPage> createState() => _LoginState();
}

class _LoginState extends ConsumerState<LoginPage> with LoginPageMixin {
  final _textNormalFontSize = 15.0;
  final _textSelectedFontSize = 17.0;
  final _loginFormKey = GlobalKey();

  double bottomHeight = 20;

  // 是否同意用户协议
  bool isAgreeProtocol = false;

  @override
  void initState() {
    super.initState();
    //监听Widget是否绘制完毕
    WidgetsBinding.instance.addPostFrameCallback(_afterLayout);
  }

  @override
  void dispose() {
    super.dispose();
  }

  // Widget绘制完成后的回调
  void _afterLayout(Duration timeStamp) async {
    Future.delayed(const Duration(milliseconds: 100), () {
      // 获取底部高度
      Size loginFormSize = _loginFormKey.size!;
      final offset = _loginFormKey.position();
      // 屏幕高度 - 登录表单高度 = 底部高度
      setState(() {
        bottomHeight = ScreenUtil.getScreenH(context) - loginFormSize.height - offset!.dy;
      });
    });
    // 清空token
    SpUtil.remove('loginData');
    // 是否记住了密码（rememberPasswordModel仅支持记住设备登录、手机号登录的密码）
    final rememberPasswordModel = SpUtil.getObj('rememberPasswordModel', (v) => RememberPasswordModel().fromJson(v),
        defValue: RememberPasswordModel(rememberPassword: false));
    if (rememberPasswordModel.rememberPassword!) {
      ref.read(rememberPasswordProvider.notifier).state = true;
      ref
          .read(globalStateProvider.notifier)
          .updateLoginType(rememberPasswordModel.loginType! == '4' ? LoginTypeEnum.device : LoginTypeEnum.phone);
    }
  }

  /// 底部
  Widget _buildBottom() {
    // ToastUtils.showToast('bottomHeight: $bottomHeight');
    return Container(
      // height: bottomHeight,
      decoration: const BoxDecoration(
          // color: Colors.green,
          ),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.end,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              // 代理商登录按钮
              Directionality(
                textDirection: TextDirection.rtl,
                child: TextButton.icon(
                  icon: const Icon(
                    Icons.arrow_back_ios,
                    color: Colors.black,
                    size: 12,
                  ),
                  onPressed: () {
                    XLogger.debug('代理商登录');
                    // 用户协议是否同意
                    if (!isAgreeProtocol) {
                      _showAgreeDialog();
                      return;
                    }
                    context.pushNamed('agent-login');
                  },
                  style: ButtonStyle(
                    backgroundColor: MaterialStateProperty.all(Colors.transparent),
                    shadowColor: MaterialStateProperty.all(Colors.transparent),
                    overlayColor: MaterialStateProperty.all(Colors.transparent),
                  ),
                  label: const Row(
                    children: [
                      Text(
                        "代理商登录",
                        style: TextStyle(color: Colors.black, fontSize: 14),
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              // 勾选框
              GestureDetector(
                onTap: () {
                  setState(() {
                    isAgreeProtocol = !isAgreeProtocol;
                  });
                },
                child: Icon(
                  isAgreeProtocol ? Icons.check_circle : Icons.circle_outlined,
                  color: isAgreeProtocol ? AppTheme.themeConfig.primaryColor : Colors.black,
                  size: 16,
                ),
              ),
              const SizedBox(
                width: 4,
              ),
              const Text(
                "阅读并同意",
                style: TextStyle(color: Colors.black, fontSize: 12),
              ),
              GestureDetector(
                onTap: () {
                  context.pushNamed('protocol',
                      queryParameters: {'title': '用户协议', 'url': 'https://www.ljwl.tech/user_agreement/index.html'});
                },
                child: Text(
                  "《用户服务协议》",
                  style: TextStyle(color: AppTheme.themeConfig.primaryColor, fontSize: 12),
                ),
              ),
              const Text(
                "和",
                style: TextStyle(color: Colors.black, fontSize: 12),
              ),
              GestureDetector(
                onTap: () {
                  context.pushNamed('protocol',
                      queryParameters: {'title': '隐私政策', 'url': 'https://www.ljwl.tech/privacy_policy/index.html'});
                },
                child: Text(
                  "《隐私政策》",
                  style: TextStyle(color: AppTheme.themeConfig.primaryColor, fontSize: 12),
                ),
              ),
            ],
          ),
          SizedBox(height: 20),

          Container(
            padding: EdgeInsets.symmetric(vertical: 0.0, horizontal: 20.0),
            child: Row(
              children: [
                Expanded(child:
                  GestureDetector(
                  onTap: () {
                    ref.read(globalStateProvider.notifier).updateLoginType(LoginTypeEnum.device);
                  },
                  child: _buildBottomText("设备号登录", LoginTypeEnum.device),
                  ),
                ),
                SizedBox(width: 20),
                Expanded(child:
                  GestureDetector(
                    onTap: () {
                      ref.read(globalStateProvider.notifier).updateLoginType(LoginTypeEnum.phone);
                    },
                    child: _buildBottomText("手机号登录", LoginTypeEnum.phone),
                  ),
                ),
                ]
            ),
          ),
          // SizedBox(
          //   height: 60,
          //   child: Row(
          //       mainAxisAlignment: MainAxisAlignment.center,
          //       crossAxisAlignment: CrossAxisAlignment.baseline,
          //       textBaseline: TextBaseline.alphabetic,
          //       children: [
          //         GestureDetector(
          //             onTap: () {
          //               ref.read(globalStateProvider.notifier).updateLoginType(LoginTypeEnum.device);
          //             },
          //             child: _buildText("设备号登录", LoginTypeEnum.device)),
          //         const SizedBox(width: 20),
          //         GestureDetector(
          //           onTap: () {
          //             ref.read(globalStateProvider.notifier).updateLoginType(LoginTypeEnum.phone);
          //           },
          //           child: _buildText("手机号登录", LoginTypeEnum.phone),
          //         )
          //       ]),
          // ),

          const SizedBox(
            height: 20,
          ),
        ],
      ),
    );
  }

  /// 构建设备登录方式文本
  Widget _buildBottomText(String text, LoginTypeEnum type) {
    final loginType = ref.watch(globalStateProvider).loginType;
    return Container(
      alignment: Alignment.center,
      height: 40,
      //在此设置
      decoration: BoxDecoration(
        color: loginType == type ? AppTheme.themeConfig.primaryColor : AppTheme.themeConfig.greyBgColor,
        borderRadius: BorderRadius.circular(6),
        border: Border.all(
          color: AppTheme.themeConfig.primaryColor,
          width: 1, // 设置边框宽度为1像素
        ),
      ),

      child: Text(
          style: TextStyle(
            color: loginType == type ? AppTheme.themeConfig.greyBgColor : AppTheme.themeConfig.primaryColor,
          ),
          text
      ),
    );
  }

  /// 构建设备登录方式文本
  AnimatedDefaultTextStyle _buildText(String text, LoginTypeEnum type) {
    final loginType = ref.watch(globalStateProvider).loginType;
    return AnimatedDefaultTextStyle(
        style: loginType == type
            ? TextStyle(
            fontSize: _textNormalFontSize, color: Colors.white, backgroundColor: AppTheme.themeConfig.primaryColor)
            : TextStyle(fontSize: _textNormalFontSize),
        duration: const Duration(milliseconds: 100),
        child: Text(text));
  }
  /// 登录事件
  void _login(LoginFormModel model) async {
    // 重置充值弹窗提示
    hasShowRechargeDialog = false;
    // 用户协议是否同意
    if (!isAgreeProtocol) {
      _showAgreeDialog();
      return;
    }
    XLogger.debug('校验通过，开始登录');
    final rememberPassword = ref.watch(rememberPasswordProvider);

    var loginData = {};
    if (model.loginType == LoginTypeEnum.device) {
      loginData['type'] = '4';
      loginData['username'] = model.imei;
      loginData['password'] = model.imeiPassword;
    } else if (model.loginType == LoginTypeEnum.phone) {
      loginData['type'] = '5';
      loginData['username'] = model.phone;
      loginData['password'] = model.phonePassword;
    }
    ToastUtils.showLoading();
    var res = await post<LoginResp, LoginResp>('/app/user/login', data: loginData, decodeType: LoginResp());
    res.when(success: (resp) {
      ToastUtils.dismissLoading();
      if (resp.code == 200) {


        SpUtil.putObject('loginData', resp.data!);
        SpUtil.putBool('isLogin', true);
        ref.read(userTypeProvider.notifier).state = UserTypeEnum.fromValue(resp.data!.type!);

        // 是否记住密码
        final rememberPasswordModel = RememberPasswordModel(rememberPassword: rememberPassword);
        if (rememberPassword) {
          rememberPasswordModel.loginType = loginData['type']!;
          rememberPasswordModel.username = loginData['username']!;
          rememberPasswordModel.password = loginData['password']!;
          SpUtil.putObject('rememberPasswordModel', rememberPasswordModel);
        } else {
          SpUtil.remove('rememberPasswordModel');
        }
        refreshDeviceInfo(() {
          ToastUtils.showToast('登录成功');
          // 登录成功
          _loginSuccess(model);
        });





      } else if (resp.code == 10001) {
        // 未绑定手机号, 跳转到绑定手机号页面
        // 保存设备号
        SpUtil.putString('tempLoginImei', model.imei);
        context.push(RouterManager.bindPhone);
      } else {
        ToastUtils.showToast(resp.msg ?? '登录失败');
      }
      XLogger.debug('登录成功');
    }, failure: (String msg, int code) {
      XLogger.error('登录失败 code: $code msg: $msg');
    });
  }

  void _loginSuccess(LoginFormModel model) {
    ToastUtils.dismissLoading();
    ToastUtils.showSuccess('登录成功');
    SpUtil.putBool('isLogin', true);
    // 延迟1秒跳转
    Future.delayed(const Duration(seconds: 1), () {
      context.go('/');
    });
  }

  /// 显示用户协议弹窗
  _showAgreeDialog() {
    showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
            title: const Text('温馨提示'),
            // 富文本
            content: Container(
                child: Text.rich(TextSpan(children: [
              const TextSpan(
                text: '请阅读并同意',
                style: TextStyle(color: Colors.black, fontSize: 14),
              ),
              TextSpan(
                text: '《用户服务协议》',
                style: TextStyle(color: AppTheme.themeConfig.primaryColor, fontSize: 14),
                recognizer: TapGestureRecognizer()
                  ..onTap = () {
                    context.pushNamed('protocol',
                        queryParameters: {'title': '用户协议', 'url': 'https://www.ljwl.tech/user_agreement/index.html'});
                  },
              ),
              const TextSpan(
                text: '及',
                style: TextStyle(color: Colors.black, fontSize: 14),
              ),
              TextSpan(
                text: '《隐私政策》',
                style: TextStyle(color: AppTheme.themeConfig.primaryColor, fontSize: 14),
                recognizer: TapGestureRecognizer()
                  ..onTap = () {
                    context.pushNamed('protocol',
                        queryParameters: {'title': '隐私政策', 'url': 'https://www.ljwl.tech/privacy_policy/index.html'});
                  },
              ),
              const TextSpan(
                text: '可继续登录',
                style: TextStyle(color: Colors.black, fontSize: 14),
              ),
            ]))),
            actions: [
              TextButton(
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                  child: const Text('取消')),
              TextButton(
                  onPressed: () {
                    setState(() {
                      isAgreeProtocol = true;
                    });
                    Navigator.of(context).pop();
                  },
                  child: const Text('同意')),
            ],
          );
        });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // resizeToAvoidBottomInset: false,
      body: Stack(children: [
        Container(
          decoration: const BoxDecoration(
            image: DecorationImage(
              image: AssetImage("assets/images/login/login_bg.png"),
              fit: BoxFit.cover,
            ),
          ),
        ),
        SingleChildScrollView(
          child: ConstrainedBox(
            constraints: BoxConstraints.expand(
              height: ScreenUtil.getScreenH(context),
            ),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                // logo
                Expanded(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Image.asset(
                        "assets/images/logo/logo_login.png",
                        width: 120,
                        height: 120,
                      ),
                      SizedBox(height: 5),
                      Text("零距物联",
                        style: TextStyle(
                          fontSize: 24.0, // 这里将字号设置为24.0，你可以根据实际需求调整该数值
                        ),
                      ),
                      SizedBox(height: 20),
                      LoginForm(key: _loginFormKey, callback: _login),
                    ],
                  ),
                ),
                // SizedBox(height: 28,),
                _buildBottom(),
              ],
            ),
          ),
        ),
      ]),
    );
  }
}

class RememberPasswordModel {
  bool? rememberPassword;
  String? loginType;
  String? username;
  String? password;

  RememberPasswordModel({this.rememberPassword, this.loginType, this.username, this.password});

  toJson() {
    return {
      'rememberPassword': rememberPassword,
      'loginType': loginType,
      'username': username,
      'password': password,
    };
  }

  fromJson(Map<dynamic, dynamic> json) {
    return RememberPasswordModel(
      rememberPassword: json['rememberPassword'],
      loginType: json['loginType'],
      username: json['username'],
      password: json['password'],
    );
  }
}
